package com.ahnchan.ContactsPlus;

import java.util.ArrayList;
import java.util.HashMap;

import com.ahnchan.ContactsPlus.CompanyActivity.CompanyAdapter;
import com.ahnchan.ContactsPlus.ContactsActivity.ContactsAdapter;
import com.ahnchan.ContactsPlus.util.ListUtils;
import com.ahnchan.ContactsPlus.util.WordUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * Group Tab
 * 
 * @author Ahnchan
 *
 */
public class GroupActivity extends ListActivity {

	private ContactsPlusSetting setting;
	private boolean bSearchFocus = false; // Search textedit focus control
	
	private GroupAdapter mGroupAdapter;
	
	private ArrayList<Group> aList;
	private ArrayList<Group> aOrgList;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.group);
        
        // Get setting info (Singleton pattern)
        setting = ContactsPlusSetting.instatnce();

        // Change initalization (every query execute)
//        mGroupAdapter = new GroupAdapter();
//        setListAdapter(mGroupAdapter);
        
        // List Click
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        
        lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				
				setting.setGroupPosition(arg2);
				
				contactList(((Group)aList.get(arg2)).getID()); 
			}
        	
        });
        
        // Search edit text event
        EditText searchEdit = (EditText)findViewById(R.id.group_search_edit);
//        searchEdit.setFocusable(false);
//        searchEdit.clearFocus();
        searchEdit.addTextChangedListener(new TextWatcher() 
        {
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				searchGroup();
			}
        });
        searchEdit.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// Found soft key hidden method 
				// Ahnchan 20110215
				// add manifest -> windowSoftInputMode 
//		        changeSearchEditFocus();
			}
		});

        // Group 
//    	showGroup();
        
    }

    @Override
    protected void onResume() {
    	
    	super.onResume();
    	
//    	mGroupAdapter = new GroupAdapter(this, aList);
//    	setListAdapter(mGroupAdapter);
    	
    	// Reload data
    	showGroup();
    	
    	// move last click position
    	ListView lv = getListView();
    	lv.setSelection(setting.getGroupPosition());
    }

    /**
     * Change search edit focusable
     */
    public void changeSearchEditFocus() {

    	if (bSearchFocus) {
    		return;
    	}

    	EditText searchEdit = (EditText)findViewById(R.id.group_search_edit);
   		searchEdit.setFocusableInTouchMode(true);
   		searchEdit.setFocusable(true);
   		searchEdit.setCursorVisible(true);
   		
   		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
   		imm.showSoftInput(searchEdit, InputMethodManager.SHOW_IMPLICIT);

   		bSearchFocus = true;
   		
    }

    // Custom Simple Adapter
    // Change Font size, control contacts photo size
    class GroupAdapter extends BaseAdapter implements SectionIndexer {

    	private Context context;
    	private ArrayList<Group> groupList;
    	
    	private int iWidth;
    	
    	/**
    	 * Constructor
    	 */
    	public GroupAdapter(Context _context, ArrayList<Group> list) {
    		context = _context;
    		groupList = list;
    	
    		iWidth = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
    	}
    	
    	public int getCount() {
    		return groupList.size();
    	}
    	
    	public Object getItem(int position) {
    		return groupList.get(position);
    	}

    	public long getItemId(int arg0) {
    		return 0;
    	}

		public View getView(int position, View convertView, ViewGroup parent) {
			
			LayoutInflater inflater = getLayoutInflater();
			View row = inflater.inflate(R.layout.group_row, parent, false);

			// Header
			LinearLayout header = (LinearLayout)row.findViewById(R.id.group_section);

			Group group = groupList.get(position);
			String strLabel = group.getName();

			if (setting.getGroupIndex()) {
				char firstChar = WordUtils.getFirstInitial(strLabel.toUpperCase(), 
															setting.getTypeSymbolNumber(),
															setting.getSpreadSymbol(),
															setting.getSpreadNumber());
				if (position == 0) {
					setSection(header, ""+firstChar);
				} else {
					String strPreLabel = groupList.get(position-1).getName();
					char preFirstChar = WordUtils.getFirstInitial(strPreLabel.toUpperCase(), 
																	setting.getTypeSymbolNumber(),
																	setting.getSpreadSymbol(),
																	setting.getSpreadNumber());
					if (firstChar != preFirstChar) {
						setSection(header, ""+firstChar);
					} else {
						header.setVisibility(View.GONE);
					}
				}
			} else {
				header.setVisibility(View.GONE);
			}
			
			TextView name = (TextView) row.findViewById(R.id.name_text);
			name.setTextSize(setting.getIntFontSize());
			name.setWidth(iWidth-100);
			name.setText(strLabel);
			
			if (setting.getGroupCount()) {
				TextView count = (TextView) row.findViewById(R.id.count_text);
				count.setTextSize(setting.getIntFontSize());
				count.setWidth(100);
				count.setText(group.getCount());
			}
			
			return row;
		}

		public void setSection(LinearLayout header, String firstChar) {
			
			TextView text = new TextView(context);
			header.setBackgroundColor(setting.getIndexTitleBGColor());
			text.setTextColor(setting.getIndexTitleColor());

			if ("0".equals(firstChar) && !setting.getSpreadNumber()) {
				firstChar = "0~9";
			}

			text.setText(firstChar);
			text.setTextSize(setting.getIndexFontSize());
			text.setPadding(5, 0, 0, 0);
			text.setGravity(Gravity.CENTER_VERTICAL);
			header.addView(text);			
		}

		public int getPositionForSection(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public int getSectionForPosition(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public Object[] getSections() {
			// TODO Auto-generated method stub
			return null;
		}
    }

    /**
     * 
     * @param member
     */
    private void contactList(String group) {
    	Intent intent = new Intent(getApplicationContext(), ContactsActivity.class);
    	intent.putExtra(ContactsActivity.TEXT_TYPE, ContactsActivity.TEXT_GROUP);
    	intent.putExtra(ContactsActivity.TEXT_DATA, group);
    	startActivity(intent);
    }
    
    private void searchGroup() {
    	
    	// Check 
    	if (null == aOrgList) return;
    	if (aOrgList.size() <= 0) return;

    	// initialize list array
    	aList = new ArrayList<Group>();

    	EditText edit = (EditText)findViewById(R.id.group_search_edit);
		String strSearch = edit.getText().toString();
		
		// Search in list
    	for(int i=0; i < aOrgList.size(); i++) {
    		Group group = aOrgList.get(i);
    		if (group.isThis(strSearch)) {
    			aList.add(group);
    		}
    	}
    	
    	mGroupAdapter = new GroupAdapter(this, aList);
    	setListAdapter(mGroupAdapter);    
    }

    private void showGroup() {
    	showGroup("");
    }
    
    /**
     * show group list  
     */
    private void showGroup(String search) {
    	
	    // Initialization list	
    	aList = new ArrayList<Group>();
//    	mGroupAdapter = new GroupAdapter(this, aList);
//    	setListAdapter(mGroupAdapter);
    	    	
    	String[] projection_data = new String[] {
    			ContactsContract.Groups._ID,
    			ContactsContract.Groups.SUMMARY_COUNT,	// Count
    			ContactsContract.Groups.TITLE
    	};

    	String selection = "";
//    	String selection = ContactsContract.Groups.DELETED + "=0" +
//    					" AND " + ContactsContract.Groups.GROUP_VISIBLE + "=1";
    	
    	// Search
    	// Remark by Ahnchan 20110119
		// Change search method. initial search, not db query
//    	if ((null != search) && (search.length()>0)) {
//    		selection += " AND " + ContactsContract.Groups.TITLE + " like '%" + search + "%'"; 
//    	}

    	String order = ContactsContract.Groups.TITLE + " COLLATE LOCALIZED ASC";

    	Cursor mCursor = getContentResolver().query(ContactsContract.Groups.CONTENT_SUMMARY_URI, 
    												projection_data, selection, null, order);

    	if (mCursor == null) {
    		return;
    	}
    		 
    	if (mCursor.moveToFirst()) {
    		
    		String strID = "";
    		String strName = "";
    		String strCount = "0";
    		
    		int iTotal = 0;
    		
    		do {
    			// Group ID
    			try {
    				strID = mCursor.getString(0);
    			} catch (Exception ex) {
    				strID = "0";
    			}
    			
    			// Group Count
    			try {
    				strCount = mCursor.getString(1);
    			} catch (Exception ex) {
    				// Organization is not existed.
    				strCount = "";
    			}

    			// Group Name
    			try {
        			strName = mCursor.getString(2);
    			} catch (Exception ex) {
    				// Organization is not existed.
    				strName = "";
    			}

    			
    			// Search
            	if ((null != search) && (search.length()>0)) {
            		if (WordUtils.isInitialSound(strName, search) || 
            		    WordUtils.isHangulInitialSound(strName, search) ||
            			(strName.toUpperCase().indexOf(search.toUpperCase()) >= 0)) {
            			// Find~~!
            		} else {
            			continue;            			
            		}
            	}
    			
    			Group group = new Group(strID, strID, strName, Integer.parseInt(strCount), strID, "");
				aList.add(group);
				
				iTotal++;
    			
    		} while (mCursor.moveToNext());
    		    		
    		setText("Count:"+iTotal);

    	} 
    	
    	// Sorting list
    	aList = ListUtils.sortList(aList, setting.getTypeList(), setting.getLocalLanguage(), "Group");
    	
    	aOrgList = aList; // Save original data
    	mCursor.close();
    	
    	mGroupAdapter = new GroupAdapter(this, aList);
    	setListAdapter(mGroupAdapter);

    	return;
    }

    /**
     * Debug code viewer
     * @param message
     */
    private void setText(String message) {
    	TextView text = (TextView)findViewById(R.id.group_text);
    	text.setText(message);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	switch (item.getItemId()) {
    	case R.id.option_setting :
    		
    		Intent intent = new Intent(this, SettingActivity.class);
    		startActivity(intent);
    		
    		return true;
    		
    	case R.id.option_about :

    		Intent aboutIntent = new Intent(this, AboutActivity.class);
    		startActivity(aboutIntent);
    		
    		return true;
    		
    	case R.id.option_refresh :
    		
    		// Initialize adapter
//        	mGroupAdapter = new GroupAdapter();
//        	setListAdapter(mGroupAdapter);
    		
    		// Clear search word 
        	EditText edit = (EditText)findViewById(R.id.group_search_edit);
        	edit.setText("");
        	
        	// Reload data
        	showGroup();

        	return true;
    		
    	case R.id.option_fontsize :
    		
    		View view = this.getLayoutInflater().inflate(R.layout.fontsize_dialog, null);
    		AlertDialog.Builder alt = new AlertDialog.Builder(this);
    		SeekBar bar = (SeekBar)view.findViewById(R.id.fontsize_seekbar);
    		bar.setProgress(setting.getIntFontSize()-setting.getMinFontSize());
//    		TextView result = (TextView)view.findViewById(R.id.fontsize_result);
//    		result.setText(getString(R.string.fontsize_result) + setting.getIntFontSize() + " " + getString(R.string.fontsize_unit));
    		bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
				public void onStopTrackingTouch(SeekBar seekBar) {
					// nothing
				}
				public void onStartTrackingTouch(SeekBar seekBar) {
					// nothing
				}
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
					// Change Dialog text (Font Size)
//		    		View view = CompanyActivity.this.getLayoutInflater().inflate(R.layout.fontsize_dialog, null);
//		    		TextView result = (TextView)view.findViewById(R.id.fontsize_result);
//		    		result.setText(getString(R.string.fontsize_result) + seekBar.getProgress() + " " + getString(R.string.fontsize_unit));						

		    		// Change list font size
					changeFontSize(seekBar.getProgress()+setting.getMinFontSize());
				}
			});
    		SeekBar barIndex = (SeekBar)view.findViewById(R.id.fontsize_seekbar_index);
    		barIndex.setMax(30);
    		barIndex.setProgress(setting.getIndexFontSize()-setting.getMinFontSize());
    		barIndex.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
				public void onStopTrackingTouch(SeekBar seekBar) {
					// nothing
				}
				public void onStartTrackingTouch(SeekBar seekBar) {
					// nothing
				}
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
					// Change list font size
					changeIndexFontSize(seekBar.getProgress()+setting.getMinFontSize());
				}
			});
    		alt.setView(view);
    		
    		AlertDialog alert = alt.create();
    		alert.show();
    		
    		return true;
    	}
    	return false;
    }	
    
    /**
     * Change list font size
     * @param fontSize
     */
    public void changeFontSize(int fontSize) {
    	setting.setFontSize(""+fontSize);
    	
    	mGroupAdapter = new GroupAdapter(this, aList);
    	setListAdapter(mGroupAdapter);    	
    }

    /**
     * Change list index font size
     * @param fontSize
     */
    public void changeIndexFontSize(int fontSize) {
    	setting.setIndexFontSize(""+fontSize);
    	
    	mGroupAdapter = new GroupAdapter(this, aList);
    	setListAdapter(mGroupAdapter);    	
    }
}
